<!-- eslint-disable vue/require-valid-default-prop -->
<script setup>
import { ref, watch } from 'vue'
import { Toast, ImagePreview } from 'vant'
import { upload } from '@/request/api'
import { removeArr } from '@/utils/tools'
import { oss } from '@/utils/config'

const props = defineProps({ list: { type: Array, default: [] } })
const emit = defineEmits(['update:list'])
const imgList = ref([])
imgList.value = [...props.list]
const afterRead = async (file) => {
  Toast.loading({
    duration: 0,
    forbidClick: false,
    message: '上传中...'
  })
  const params = new FormData()
  // 单张图片上传
  let imgObj
  if (file.file.size > 1572864) {
    imgObj = await dataURLtoFile(file)
  } else {
    imgObj = file.file
  }
  params.append('files', imgObj)

  console.log(imgObj)
  const { code, data } = await upload(params)
  Toast.clear()
  if (code === 0) {
    Toast('上传成功')
    console.log(data)
    imgList.value = [...imgList.value, ...data]
  } else {
    Toast('上传失败')
  }
}
/* 图片压缩 */
const dataURLtoFile = async (file) => {
  return new Promise((resolve) => {
    const canvas = document.createElement('canvas')
    const ctx = canvas.getContext('2d')
    const img = new Image()
    img.src = file.content
    img.onload = function () {
      const oldWidth = img.width
      const oldHeight = img.height
      const quality = 0.7
      canvas.width = oldWidth
      canvas.height = oldHeight
      ctx.drawImage(img, 0, 0, oldWidth, oldHeight)
      const base64 = canvas.toDataURL(file.file.type, quality)
      const arr = base64.split(',')
      const mime = arr[0].match(/:(.*?);/)[1]
      const bstr = atob(arr[1])
      let n = bstr.length
      const u8arr = new Uint8Array(n)
      while (n--) {
        u8arr[n] = bstr.charCodeAt(n)
      }
      resolve(new File([u8arr], file.file.name, { type: mime }))
    }
  })
}
watch(imgList, (newVal, oldVal) => {
  emit('update:list', newVal)
})
const removeImg = (e) => {
  removeArr(imgList.value, e)
}
// 大图
const bigImg = (e) => {
  ImagePreview({
    images: imgList.value,
    startPosition: e
  })
}
</script>

<template>
  <lay-row>
    <lay-coloms :column="4" v-for="(item, index) in imgList" :key="index">
      <van-icon
        :name="oss + '/nutrition/web/%E7%BB%84%201%20%E6%8B%B7%E8%B4%9D.png'"
        @click="removeImg(item)"
      />
      <img :src="item" alt="" @click="bigImg(index)" />
    </lay-coloms>

    <lay-coloms :column="4" v-if="imgList.length < 8">
      <van-uploader :after-read="afterRead" />
    </lay-coloms>
  </lay-row>
</template>
<style lang="scss" scoped>
.column {
  position: relative;
  .van-icon {
    position: absolute;
    top: -2px;
    left: -2px;
    color: #357efe;
    z-index: 10;
  }
}
img {
  width: 75px;
  height: 75px;
  border-radius: 6px;
  position: relative;
}
.van-uploader,
.van-uploader__wrapper {
  &:deep(.van-uploader__upload) {
    width: 75px;
    height: 75px;
    margin: 0;
    border-radius: 6px;
    background: #f6fafd;
  }
}
</style>
